<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";
import BaseSelect from "@/components/BaseSelect.vue";

const route = useRoute();
const router = useRouter();

// 状态选项
const statusOptions = ref([
  { value: "1", text: "营业中" },
  { value: "0", text: "已关闭" },
]);

// 门店级别选项
const levelOptions = ref([
  { value: "0", text: "无星级" },
  { value: "1", text: "一星级" },
  { value: "2", text: "三星级" },
  { value: "3", text: "五星级" },
  { value: "4", text: "七星级" }
]);

// 地区数据
const provinceOptions = ref([]);
const cityOptions = ref([]);
const districtOptions = ref([]);

const isEdit = computed(() => route.name === 'StoreEdit');

// 表单数据
const formData = ref({
  id: null,
  store_code: "",
  name: "",
  contact_person: "",
  contact_phone: "",
  area_code: "",
  address: "",
  store_level: "1",
  status: "1",
  created_at: null,
  updated_at: null,
});

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 获取地区数据
const fetchAreas = async (type, parentCode = '') => {
  try {
    const params = { type };
    if (parentCode) params.code = parentCode;
    
    const res = await get("/city/list", params);
    
    if (res.code === 200) {
      return res.data.map(item => ({
        code: item.code,
        name: item.name
      }));
    }
    return [];
  } catch (error) {
    console.error("获取地区数据失败", error);
    return [];
  }
};

// 加载省份数据
const loadProvinces = async () => {
  const provinces = await fetchAreas('province');
  provinceOptions.value = provinces.map(p => ({
    value: p.code,
    text: p.name
  }));
};

// 省份变化时加载城市
const handleProvinceChange = async (code) => {
  formData.value.city = ''; // 清空城市
  formData.value.district = ''; // 清空区县
  cityOptions.value = [];
  districtOptions.value = [];
  
  if (code) {
    const cities = await fetchAreas('city', code);
    cityOptions.value = cities.map(c => ({
      value: c.code,
      text: c.name
    }));
  }
};

// 城市变化时加载区县
const handleCityChange = async (code) => {
  formData.value.district = ''; // 清空区县
  districtOptions.value = [];
  
  if (code) {
    const districts = await fetchAreas('district', code);
    districtOptions.value = districts.map(d => ({
      value: d.code,
      text: d.name
    }));
  }
};

// 区县变化时更新area_code
const handleDistrictChange = (code) => {
  formData.value.area_code = code;
};

// 获取门店详情
const fetchStoreDetail = async (id) => {
  try {
    const res = await get("/store/detail", { id });
    if (res.code === 200 && res.data) {
      // 解析area_code获取省市区代码
      const areaCode = res.data.area_code;
      const provinceCode = areaCode.substring(0, 2) + '0000';
      const cityCode = areaCode.substring(0, 4) + '00';
      
      // 设置表单数据
      formData.value = {
        id: res.data.id,
        store_code: res.data.store_code || "",
        name: res.data.name || "",
        province: provinceCode, // 使用省代码作为value
        city: cityCode, // 使用市代码作为value
        district: areaCode, // 使用区代码作为value
        contact_person: res.data.contact_person || "",
        contact_phone: res.data.contact_phone || "",
        area_code: res.data.area_code || "",
        address: res.data.address || "",
        store_level: res.data.store_level || "1",
        status: res.data.status || "1",
        created_at: res.data.created_at,
        updated_at: res.data.updated_at,
      };
      
      // 如果编辑模式，加载对应的城市和区县
      if (isEdit.value) {
        // 加载省份数据（确保已加载）
        await loadProvinces();
        
        // 加载城市数据
        const cities = await fetchAreas('city', provinceCode);
        cityOptions.value = cities.map(c => ({
          value: c.code,
          text: c.name
        }));
        
        // 加载区县数据
        const districts = await fetchAreas('district', cityCode);
        districtOptions.value = districts.map(d => ({
          value: d.code,
          text: d.name
        }));
      }
    }
  } catch (error) {
    vToast.error("获取门店详情失败");
    console.error(error);
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 验证逻辑
    if (!formData.value.store_code) {
      vToast.warning("请输入门店编码");
      return;
    }
    
    if (!formData.value.name) {
      vToast.warning("请输入门店名称");
      return;
    }
    
    if (!formData.value.contact_phone) {
      vToast.warning("请输入联系电话");
      return;
    }
    
    if (!formData.value.area_code) {
      vToast.warning("请选择所在地区");
      return;
    }

    // 准备提交数据
    const data = {
      ...formData.value,
      // 移除不需要的字段
      province: undefined,
      city: undefined,
      district: undefined
    };
    
    // 如果是新增模式，移除ID
    if (!isEdit.value) {
      delete data.id;
      delete data.created_at;
      delete data.updated_at;
    }

    const api = isEdit.value ? "/store/update" : "/store/add";
    const res = await post(api, data);

    if (res.code === 200) {
      vToast.success(isEdit.value ? "门店更新成功" : "门店添加成功");
      router.push("/store");
    } else {
      vToast.error(res.msg || "操作失败");
    }
  } catch (error) {
    vToast.error("提交失败");
    console.error(error);
  }
};

// 返回
const goBack = () => {
  router.push("/store");
};

// 初始化
onMounted(() => {
  loadProvinces();
  if (isEdit.value && route.params.id) {
    fetchStoreDetail(route.params.id);
  } else {
    // 设置默认值
    formData.value.store_level = "1";
    formData.value.status = "1";
  }
});
</script>

<template>
  <div class="store-edit page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <router-link to="/store">
            <span class="text">门店管理</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">{{ isEdit ? '编辑门店' : '添加门店' }}</span>
        </div>
      </div>
      <h1 class="page-title">{{ isEdit ? '编辑门店' : '添加门店' }}</h1>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <form class="v-form" @submit.prevent="submitForm">
        <!-- 基本信息卡片 -->
        <div class="v-card">
          <div class="card-header">
            <h3>基本信息</h3>
          </div>
          <div class="card-body">
            <div class="form-grid">
              <!-- 门店编码 -->
              <div class="form-group">
                <label class="form-label">门店编码</label>
                <input
                  v-model="formData.store_code"
                  type="text"
                  class="form-input"
                  placeholder="请输入门店编码"
                  required
                />
              </div>

              <!-- 门店名称 -->
              <div class="form-group">
                <label class="form-label">门店名称</label>
                <input
                  v-model="formData.name"
                  type="text"
                  class="form-input"
                  placeholder="请输入门店名称"
                  required
                />
              </div>

              <!-- 联系人 -->
              <div class="form-group">
                <label class="form-label">联系人</label>
                <input
                  v-model="formData.contact_person"
                  type="text"
                  class="form-input"
                  placeholder="请输入联系人"
                />
              </div>

              <!-- 联系电话 -->
              <div class="form-group">
                <label class="form-label">联系电话</label>
                <input
                  v-model="formData.contact_phone"
                  type="text"
                  class="form-input"
                  placeholder="请输入联系电话"
                  required
                />
              </div>

              <!-- 所在地区 -->
              <div class="form-group">
                <label class="form-label">所在地区（不修改请不要动）</label>
                <div class="area-selectors">
                  <BaseSelect
                    v-model="formData.province"
                    :options="provinceOptions"
                    placeholder="请选择省"
                    @change="handleProvinceChange"
                  />
                  <BaseSelect
                    v-model="formData.city"
                    :options="cityOptions"
                    placeholder="请选择市"
                    @change="handleCityChange"
                    :disabled="!formData.province"
                  />
                  <BaseSelect
                    v-model="formData.district"
                    :options="districtOptions"
                    placeholder="请选择区县"
                    @change="handleDistrictChange"
                    :disabled="!formData.city"
                  />
                </div>
              </div>

              <!-- 详细地址 -->
              <div class="form-group full-width">
                <label class="form-label">详细地址</label>
                <input
                  v-model="formData.address"
                  type="text"
                  class="form-input"
                  placeholder="请输入详细地址"
                />
              </div>

              <!-- 门店级别 -->
              <div class="form-group">
                <label class="form-label">门店级别</label>
                <BaseSelect
                  v-model="formData.store_level"
                  :options="levelOptions"
                  placeholder="请选择级别"
                />
              </div>

              <!-- 状态 -->
              <div class="form-group">
                <label class="form-label">状态</label>
                <BaseSelect
                  v-model="formData.status"
                  :options="statusOptions"
                  placeholder="请选择状态"
                />
              </div>

              <!-- 创建时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">创建时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.created_at)"
                  disabled
                />
              </div>

              <!-- 更新时间 -->
              <div class="form-group" v-if="isEdit">
                <label class="form-label">更新时间</label>
                <input
                  type="text"
                  class="form-input"
                  :value="formatTimestamp(formData.updated_at)"
                  disabled
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 表单操作按钮 -->
        <div class="form-actions">
          <button type="submit" class="v-button primary">提交保存</button>
          <button type="button" class="v-button" @click="goBack">返回</button>
        </div>
      </form>
    </div>
  </div>
</template>

<style scoped lang="less">
.store-edit {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .form-container {
    width: 100%;
    padding: 20px;
  }

  .v-card {
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    
    .card-header {
      padding: 16px 20px;
      border-bottom: 1px solid #eee;
      
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 500;
        color: #333;
      }
    }
    
    .card-body {
      padding: 20px;
    }
  }

  .form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .form-group {
      margin-bottom: 15px;
      
      &.full-width {
        grid-column: 1 / -1;
      }
      
      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }
      
      .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
        
        &:disabled {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }
      
      .area-selectors {
        display: flex;
        gap: 10px;
        
        .v-select {
          flex: 1;
        }
      }
    }
  }

  .form-actions {
    display: flex;
    justify-content: center;
    gap: 15px;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #eee;
    
    .v-button {
      min-width: 120px;
      height: 40px;
      padding: 0 20px;
      border-radius: 4px;
      font-size: 14px;
      cursor: pointer;
      
      &.primary {
        background-color: var(--v-theme);
        color: white;
        border: none;
        
        &:hover {
          background-color: var(--v-sidebar-background);
        }
      }
      
      &:not(.primary) {
        background-color: #fff;
        border: 1px solid #ddd;
        color: #333;
        
        &:hover {
          border-color: var(--v-theme);
          color: var(--v-theme);
        }
      }
    }
  }
}
</style>